<template>
  <basic-container>
    <el-tabs v-model="activeName" style="margin: 0 10px" @tab-click="handleTabClick">
      <el-tab-pane label="工站单价" name="station"> </el-tab-pane>
      <el-tab-pane label="工段单价" name="section"> </el-tab-pane>
    </el-tabs>
    <avue-crud
      class="custom-table"
      :option="option"
      :table-loading="loading"
      :data="tableData"
      :page.sync="page"
      ref="crud"
      :search.sync="query"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      :summary-method="summaryMethod"
    >
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-download" @click="handleExport" v-if="this.activeName === 'section'">导出</el-button>
      </template>
    </avue-crud>

    <export-comp
      v-if="option"
      ref="exportComp"
      page-api-url="mes-abacus/statProductionDay/query-page/work-section-production-value"
      :option="option"
      :page="page"
      :query="exportParams"
      file-name="工段单价"
    >
    </export-comp>
  </basic-container>
</template>

<script>
import { getColum, getDataList, getWorkSectionColum, getWorkSectionDataList } from '@/api/report/report';
import exportComp from '@/components/export-comp';

export default {
  name: 'outputValueCalculationReport',
  components: { exportComp },
  data() {
    return {
      activeName: 'station',
      query: {},
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 1
      },
      exportParams: {},
      searchLabelWidth: 100,
      tableData: [],
      isSummary: false,
      option: {
        searchShow: true,
        indexFixed: true,
        searchMenuSpan: 6,
        border: true,
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        index: true,
        menu: false,
        showSummary: true,
        indexLabel: '序号',
        column: []
      }
    };
  },
  async created() {
    await this.getOptionColumn();
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    async getOptionColumn() {
      try {
        const API_MAP = {
          station: getColum,
          section: getWorkSectionColum
        };
        const res = await API_MAP[this.activeName]();
        res.data.data.forEach((item) => {
          if (item.prop === 'summary') {
            item.fixed = 'right';
          }
          if (item.prop === 'dayDate') {
            item.fixed = 'left';
          }
        });
        const column = [
          ...res.data.data,
          {
            label: '时间范围',
            minWidth: 150,
            prop: 'examineDate',
            type: 'datetime',
            search: true,
            searchOrder: 7,
            hide: true,
            searchType: 'daterange',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            searchSpan: 8,
            searchLabelWidth: 150,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              }
            },
            searchRules: [
              {
                required: true,
                message: '请选择时间范围',
                trigger: 'blur'
              }
            ]
          }
        ];
        this.$set(this.option, 'column', column);
      } catch (e) {
        console.warn(e);
      }
    },
    async onLoad() {
      if (!this.query.examineDate) {
        this.$message.warning('请选择时间范围！');
        return;
      }
      this.loading = true;
      this.isSummary = false;
      const params = { startDate: this.query.examineDate[0], endDate: this.query.examineDate[1], current: this.page.currentPage, size: this.page.pageSize };
      try {
        const API_MAP = {
          station: getDataList,
          section: getWorkSectionDataList
        };
        const res = await API_MAP[this.activeName](params);
        const data = res.data.data;
        this.page.total = data.total;
        this.tableData = data.records;
        this.isSummary = true;
      } catch (e) {
        console.log(e);
      } finally {
        this.loading = false;
      }
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad();
      done();
    },
    searchReset() {
      this.query = {};
      this.tableData = [];
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    async handleTabClick({ name }) {
      await this.getOptionColumn();
      this.tableData = [];
    },
    summaryMethod({ columns, data }) {
      let sums = [];
      if (columns.length > 0 && this.isSummary) {
        columns.forEach((column, index) => {
          let prop = column.property;
          if (prop) {
            let values = this.tableData.map((item) => {
              // 格式化数据 转整数避免浮点数计算陷阱
              return Number(item[prop]) * 100 || 0;
            });
            // 这边是列汇总数据  需要/100 还原并且保留2位
            let all =
              values.length !== 0
                ? (sums[index] = (
                    values.reduce((a, b) => {
                      return a + b;
                    }) / 100
                  ).toFixed(2))
                : 0;
            if (prop == 'summary') {
              sums[index] = all;
            } else if (prop === 'dayDate') {
              sums[index] = '合计';
            }
          } else {
            return '-';
          }
        });
      }
      return sums;
    },
    handleExport() {
      if (!this.query.examineDate) {
        this.$message.warning('请选择时间范围！');
        return;
      }
      this.exportParams = { startDate: this.query.examineDate[0], endDate: this.query.examineDate[1], current: this.page.currentPage, size: this.page.pageSize };
      this.$refs.exportComp.visible = true;
    }
  }
};
</script>

<style scoped lang="scss">
.custom-table {
  height: calc(100vh);
  overflow-y: scroll;
}
</style>
